package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.Query;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import com.itheima.entity.ShoppingCart;
import com.itheima.service.ShoppongCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/shoppingCart")

public class ShoppingCartController {
    @Autowired
    private ShoppongCartService shoppongCartService;

    @PostMapping("/add")
    public R<ShoppingCart>  add(@RequestBody ShoppingCart shoppingCart){
  log.info("购物车数据 {}",shoppingCart);
      //设置用户id，指定是那个用户的购物车数据
        Long currentId = BaseContext.getCurrentId();
        shoppingCart.setUserId(currentId);

        //查询当前菜品或者套餐是否在购物车中
        Long dishId = shoppingCart.getDishId();
        LambdaQueryWrapper<ShoppingCart> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,currentId);

        if(dishId!=null){
            //添加到购物车的是菜品
            queryWrapper.eq(ShoppingCart::getDishId,dishId);

        }else {
            //添加到购物车的是套餐


        }
        ShoppingCart cartServiceOne = shoppongCartService.getOne(queryWrapper);

        if (cartServiceOne!=null){
         Integer number = Integer.valueOf(cartServiceOne.getName());

         shoppongCartService.updateById(cartServiceOne);

        }else{
            shoppingCart.setNumber(1);
            shoppongCartService.save(shoppingCart);
            cartServiceOne=shoppingCart;
        }
        //如果已经存在就在原来的基础数量上加1

        //如果不存在，添加到购物车


        return R.success(cartServiceOne);
    }
}
